//index.js
const app = getApp()
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({
  data: {
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    userInfoFlagYes: true,
    userInfoFlagNo: false,
    makePhoneFlag: true,
    queryResult: '',
    activeIndex: 1,
    sliderOffset: 0,
    sliderLeft: 0,
    requestResult: '',
    inputShowed: false,
    inputVal: "",
    addPlayFlag:false,
    hasMoreData: true,
    isRefreshing: false,
    isLoadingMoreData: false
  },

  onPullDownRefresh: function () {
    if (this.data.isRefreshing || this.data.isLoadingMoreData) {
      return
    }
    this.setData({
      isRefreshing: true,
      hasMoreData: true
    })
    this.onQuery();
  },


  onLoad: function() {
    this.onQuery((this.data.page));
    var that = this;

    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              app.globalData.nickName = res.userInfo.nickName
              app.globalData.avatarUrl = res.userInfo.avatarUrl
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName,
                userInfo: res.userInfo
                })
            }
          })
        }
      }
    })
  },

  QryPlayDetail: function (e) {
    console.log("列表跳转详情页参数：" + e.currentTarget.dataset.id)
    console.log("列表跳转详情页参数中_id值为：" + e.currentTarget.dataset.id._id)
    wx.navigateTo({
      url: '../playdetail/playdetail?id=' + e.currentTarget.dataset.id._id,
    })
  },

  onQuery: function (page) {
    wx.showLoading({
      title: '数据查询中',
    })
    var that = this;
    const db = wx.cloud.database();
    // 获取总数
    db.collection('EPIDEMICINFO').count({
      success: function (res) {
        console.log("签到分页查询记录数为：" + res.total)
        that.data.totalCount = res.total;
      }
    })

    db.collection('EPIDEMICINFO').limit(10) // 限制返回数量为 10 条
      .orderBy('currenttime', 'desc').get({
      success: res => {
        that.data.queryResult = res.data;
        this.setData({
          queryResult: that.data.queryResult
        })
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏加载
        wx.stopPullDownRefresh();
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  /**
   * 分享给好友
   */
  onShareAppMessage: function () {
    this.setData({
      makePhoneFlag: true
    })

    return {
      title: "近期活动列表",
      imageUrl: "https://6765-geekclub-release-1300915894.tcb.qcloud.la/or4rU5F8jBFJ14GTVhhx85Qid2zY/HJ/timg.jpg?sign=bf0701c73ce9c6425c7319c98b301fe6&t=1577288070",
      path: "/pages/index/index"
    }
  },

  /**
   * 分页处理函数
   */
  onReachBottom: function () {
    var that = this;
    var temp = [];
    // 获取后面十条
    if (this.data.queryResult.length < this.data.totalCount) {
      console.log("分页查询，当前skip的值为：" + this.data.queryResult.length);
      try {
        const db = wx.cloud.database();
        db.collection('EPIDEMICINFO')
          .skip(this.data.queryResult.length)
          .limit(10) // 限制返回数量为 10 条
          .orderBy('currenttime', 'desc') // 排序
          .get({
            success: function (res) {
              // res.data 是包含以上定义的两条记录的数组
              console.log(res.data);
              if (res.data.length > 0) {
                for (var i = 0; i < res.data.length; i++) {
                  var tempTopic = res.data[i];
                  temp.push(tempTopic);
                }
                var totalactivies = {};
                totalactivies = that.data.queryResult.concat(temp);
                that.setData({
                  queryResult: totalactivies,
                })
              } else {
                wx.showToast({
                  title: '没有更多数据了',
                })
              }
            },
            fail: function (event) {
              console.log("======" + event);
            }
          })
      } catch (e) {
        console.error(e);
      }
    } else {
      wx.showToast({
        title: '没有更多数据了',
      })
    }
  }
})
